package main

import "net"

type AppInfo struct {
	Name string
	Net  net.Conn
}

type AppManager struct {
	apps []AppInfo
}

func AppManagerNew() (*AppManager, error) {
	am := &AppManager{}
	return am, nil
}

func (ap *AppManager) AllApps() *[]AppInfo {
	return &ap.apps
}

func (ap *AppInfo) IsSelf(conn net.Conn) bool {
	return ap.Net == conn
}

func (ap *AppManager) Find(name string) *AppInfo {
	for i, k := range ap.apps {
		if k.Name == name {
			return &ap.apps[i]
		}
	}
	return nil
}

func (ap *AppManager) add(info AppInfo) (int, error) {
	for _, k := range ap.apps {
		if k.Name == info.Name {
			return len(ap.apps), nil
		}
	}
	ap.apps = append(ap.apps, info)
	return len(ap.apps), nil
}

func (ap *AppManager) del(info AppInfo) (int, error) {
	for i, k := range ap.apps {
		if k.Name == info.Name {
			ap.apps = append(ap.apps[:i], ap.apps[i+1:]...)
			return len(ap.apps), nil
		}
	}
	return len(ap.apps), nil
}

func (ap *AppManager) AppManagerAdd(info AppInfo) (int, error) {
	return ap.add(info)
}

func (ap *AppManager) AppManagerDel(info AppInfo) (int, error) {
	return ap.del(info)
}

func (ap *AppManager) AppManagerDelConn(conn net.Conn) error {
	for i, k := range ap.apps {
		if k.Net == conn {
			ap.apps = append(ap.apps[:i], ap.apps[i+1:]...)
			return nil
		}
	}
	return nil
}
